﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DefeatEpidemic.Models;
using DefeatEpidemic.Common;
using LinqKit;
using DefeatEpidemic.Base;
using Microsoft.AspNetCore.Http;

namespace DefeatEpidemic.Controllers
{
    [SignFilter]
    public class CommunitiesController : Controller
    {
        private readonly DefeatEpidemicContext _context;

        public CommunitiesController(DefeatEpidemicContext context)
        {
            _context = context;
        }

        // GET: Communities
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GetList(string name, int pageindex = 1, int pagesize = 15)
        {
            Response resp = new Response();
            try
            {
                int start = (pageindex - 1) * pagesize;
                var where = PredicateBuilder.New<Community>(true);
                if (!string.IsNullOrEmpty(name))
                    where.And(u => u.name.Contains(name));
                var communities = _context.Community
                    .Where(where);
                resp.code = 1;
                resp.data = new { items = communities.Skip(start).Take(pagesize), total = communities.Count() };
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"检索出错,{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }


        [HttpGet]
        public ActionResult GetManagers(Guid community_id, int pageindex = 1, int pagesize = 15)
        {
            Response resp = new Response();
            try
            {
                int start = (pageindex - 1) * pagesize;
                var members = _context.Members.Where(u => u.community.id == community_id && u.role_type == 2)
                    .Select(u => new { u.name, u.id, u.idcard, u.mobile, u.address, u.remark });
                resp.code = 1;
                resp.data = new { total = members.Count(), items = members.Skip(start).Take(pagesize) };
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<IActionResult> AddManager(RequestModels.AddManagerModel model)
        {
            Response resp = new Response();
            try
            {
                var community = await _context.Community.FindAsync(model.community_id);
                if (_context.Members.Count(u => u.idcard == model.m_idcard || u.mobile == model.m_mobile && u.role_type == 2) > 0)
                {
                    resp.code = -1;
                    resp.message = "已添过加该管理员";
                    return Json(resp);
                }
                string managername = this.HttpContext.Session.GetString(Constants.USERID);
                var manager = _context.Managers.Where(u => u.name == managername).FirstOrDefault();
                if (manager.role_type == 1)
                {
                    await _context.Entry(manager).Reference(d => d.community).LoadAsync();
                    if (manager.community.id != model.community_id)
                    {
                        resp.code = -1;
                        resp.message = $"您是【{manager.community.name}】的管理员，不能添加其他小区的物管人员";
                        return Json(resp);
                    }
                }
                var member = new Member()
                {
                    name = model.m_name,
                    idcard = model.m_idcard,
                    mobile = model.m_mobile,
                    address = model.m_address,
                    role_type = 2,
                    remark = model.m_remark,
                    community = community
                };
                _context.Add(member);
                int ret = await _context.SaveChangesAsync();
                if (ret > 0)
                {
                    resp.code = 1;
                    resp.message = "添加成功";
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message}.{ex.StackTrace}";
            }
            return Json(resp);
        }

        /// <summary>
        /// 删除管理人员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<IActionResult> DeleteManager(Guid member_id, Guid community_id)
        {
            Response resp = new Response();
            try
            {                
                string managername = this.HttpContext.Session.GetString(Constants.USERID);
                var manager = _context.Managers.Where(u => u.name == managername).FirstOrDefault();
                if (manager.role_type == 1)
                {
                    await _context.Entry(manager).Reference(d => d.community).LoadAsync();
                    if (manager.community.id != community_id)
                    {
                        resp.code = -1;
                        resp.message = $"您是【{manager.community.name}】的管理员，不能添加其他小区的物管人员";
                        return Json(resp);
                    }
                }
                var member = await _context.Members.FindAsync(member_id);
                var oauth = _context.Wxoauths.Where(u => u.member.id == member_id).FirstOrDefault();
                if (oauth != null)
                {
                    _context.Remove(oauth);
                }
                _context.Remove(member);
                int ret = await _context.SaveChangesAsync();
                if (ret > 0)
                {
                    resp.code = 1;
                    resp.message = "删除成功";
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message}.{ex.StackTrace}";
            }
            return Json(resp);

        }
        // GET: Communities/Details/5
        public async Task<IActionResult> Details(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var community = await _context.Community
                .FirstOrDefaultAsync(m => m.id == id);
            if (community == null)
            {
                return NotFound();
            }

            return View(community);
        }

        // GET: Communities/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Communities/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("id,name,province,city,area,detail,created_at,labelNumber,status")] Community community)
        {
            Response resp = new Response();
            if (ModelState.IsValid)
            {
                _context.Add(community);
                int ret = await _context.SaveChangesAsync();
                if (ret > 0)
                {
                    resp.code = 1;
                    resp.message = "创建成功";
                }
            }
            else
            {
                resp.code = -1;
                resp.message = "error:模型验证不通过";
            }
            return Json(resp);
        }

        // GET: Communities/Edit/5
        public async Task<IActionResult> Edit(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var community = await _context.Community.FindAsync(id);
            if (community == null)
            {
                return NotFound();
            }
            return View(community);
        }

        // POST: Communities/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(Guid id, [Bind("id,name,province,city,area,detail,created_at,labelNumber,status")] Community community)
        {
            Response resp = new Response();
            if (id != community.id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(community);
                    int ret = await _context.SaveChangesAsync();
                    if (ret > 0)
                    {
                        resp.code = 1;
                        resp.message = "更新成功";
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    resp.code = -1;
                    resp.message = "更新失败";
                    if (!CommunityExists(community.id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }

                }
                //return RedirectToAction(nameof(Index));
            }
            return Json(resp);
        }

        // GET: Communities/Delete/5
        public async Task<IActionResult> Delete(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var community = await _context.Community
                .FirstOrDefaultAsync(m => m.id == id);
            if (community == null)
            {
                return NotFound();
            }

            return View(community);
        }

        // POST: Communities/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(Guid id)
        {
            Response resp = new Response();
            string managername= this.HttpContext.Session.GetString(Constants.USERID);
            var manager = _context.Managers.Where(u => u.name == managername).FirstOrDefault();
            if (manager.role_type == 2)
            {
                var community = await _context.Community.FindAsync(id);
                _context.Community.Remove(community);
                int ret = await _context.SaveChangesAsync();
                if (ret > 0)
                {
                    resp.code = 1;
                    resp.message = "删除成功";
                }
            }
            else
            {
                resp.code = -1;
                resp.message = "您没有删除权限";
            }
            //return RedirectToAction(nameof(Index));
            return Json(resp);
        }

        private bool CommunityExists(Guid id)
        {
            return _context.Community.Any(e => e.id == id);
        }
    }
}
